import createHistory from 'history/createBrowserHistory'
import { Toast } from 'antd-mobile'
import Helper from './helper'
import {pipeline} from '../helper/fetching'
const history = createHistory({
  forceRefresh: true, // 从服务器重新拉取数据
})

class Company extends Helper{
  constructor(name) {
    super()
    this.name = name
    this.init()
  }

  init() {
    this.select()
    this.isLogin()
    this.zhuge()
  }

  select() { // 关注
    const $ = this.$, me = $('.js_guanzhu'), img = me.find('img')
    me.on('click', () => {
      const {is_followed, company_id} = me.data()
      const _src = img.attr('_src'), src = img.attr('src')
      if(is_followed) { // 取消关注
        pipeline(':ve.mobile.interface/user/unfollow_company', {company_id})
          .then( data => {
            if(data.status === 0){
              return this.Toast(data.errMsg, 2)
            }
            Toast.success('取消关注', 2)
            img.attr('_src', src)
            img.attr('src', _src)
            me.data('is_followed', 0)
            window.zhuge.track('取消关注企业')
        })
      } else { // 关注
        pipeline(':ve.mobile.interface/user/follow_company' ,{company_id})
          .then(data => {
            if (data.status === 0){
              const msg = data.errMsg
              const pathname = window.location.pathname
              if(msg === '未登陆') {
                return this.goLogin(history, `${pathname}`)
              }
              return this.Toast(msg, 2)
            } else { // success
              Toast.success('关注成功', 2)
              img.attr('_src', src)
              img.attr('src', _src)
              me.data('is_followed', 1)
              window.zhuge.track('关注企业')
            }
          })
      }
    })
  }

  isLogin() {
    const $ = this.$, me = $('.js_login')
    me.on('click', () => {
      const pathname = window.location.pathname
      window.zhuge.track('注册页面打开', {
        '触发来源': '获取联系方式',
      })
      this.goLogin(history, `${pathname}`)
    })
  }

  zhuge() {
    const $ = this.$, zhuge_position = $('.js_zhuge_position');
    zhuge_position.on('click', () => {
      window.zhuge.track('招聘职位')
    })
  }
}

export default Company